import { WereWolfModule } from "@/werewolf/module";
import { WereWolfRole } from "@/werewolf/player";

export class WereWolfCheckEndPhase extends WereWolfModule.State {
    override onEnter(): void {
        this.checkEnd();
        this.popState();
    }

    checkEnd() {
        const players = this.context.players.filter((p) => !p.dead);
        let wolfCnt = 0;
        let godCnt = 0;
        let villagerCnt = 0;
        for (const p of players) {
            if (p.role == WereWolfRole.Werewolf) {
                wolfCnt++;
            } else if (
                p.role == WereWolfRole.Witch ||
                p.role == WereWolfRole.Seer ||
                p.role == WereWolfRole.Hunter
            ) {
                godCnt++;
            } else {
                villagerCnt++;
            }
        }
        if (wolfCnt === 0) {
            this.context.winner = "villagers";
            return; // 一旦有结果，立即结束判定
        }

        // 2. 狼人胜利条件（关键补充）：狼人数量达到或超过好人数量
        if (wolfCnt >= godCnt + villagerCnt) {
            this.context.winner = "werewolves";
            return;
        }

        // 3. 狼人胜利条件（根据配置）
        if (!this.context.config.fullKill) {
            // 屠边局：神或民的一方被杀光
            if (godCnt === 0 || villagerCnt === 0) {
                this.context.winner = "werewolves";
            }
        } else {
            // 屠城局：所有好人（神+民）都被杀光
            if (godCnt + villagerCnt === 0) {
                this.context.winner = "werewolves";
            }
        }
    }
}
